/*
 * Copyright (c) Jack魏 2023 - 2024, All Rights Reserved.
 */

package cn.jackwei.yiyi.service;

import cn.hutool.core.util.StrUtil;
import cn.jackwei.yiyi.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件服务类
 *
 * @author Jack魏
 * @since 2023/11/19 17:51
 */
@Slf4j
@Service
public class FileService {
    @Value("${yiyi.file.path}")
    public String filePath;

    /**
     * 多文件上传
     *
     * @param files 多文件
     * @return 是否成功
     */
    public Result<String> upload(MultipartFile[] files) {
        List<String> names = new ArrayList<>();
        try {
            for (MultipartFile file : files) {
                File saveFile = new File(filePath + File.separator + file.getOriginalFilename());
                FileCopyUtils.copy(file.getInputStream(), Files.newOutputStream(saveFile.toPath()));
                names.add(file.getOriginalFilename());
            }
        } catch (Exception exception) {
            log.error("上传文件出错！", exception);
        }
        Result<String> result = Result.successMsg("上传成功");
        result.setData(StrUtil.join(StrUtil.COMMA, names));
        return result;
    }
}
